<script setup lang="ts">
import { nextTick, ref, toRef, watch } from 'vue'
import { FullScreen, Help } from '@element-plus/icons-vue'
import useFullscreen from './useFullscreen'
import useRenderLabel from './useRenderLabel'
import useWrapStyle from './useWrapStyle'
import useMouseScale from './useMouseScale'
import VueOkrTree from '@/libs/vue-okr-tree/OkrTree.vue'
import type { IndicatorsGraph } from '@/types'

const props = withDefaults(
  defineProps<{
    visible?: boolean
    lists: IndicatorsGraph[][]
  }>(),
  {
    visible: true,
  },
)
const emits = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'use-demo'): void
}>()
function clickBack() {
  emits('update:visible', false)
}

const boxRef = ref<HTMLElement | null>(null)
const wrapRef = ref<HTMLElement | null>(null)
const fullRef = ref<HTMLElement | null>(null)

const { toggleMode } = useFullscreen(boxRef)
const { treeNodeRender } = useRenderLabel()
const { scale, onMousewheel } = useMouseScale()

const { left, top, wrapWidth, setCenter } = useWrapStyle({
  wrapRef,
  boxRef,
  lists: toRef(() => props.lists),
  scale,
})

function clickDemo() {
  emits('use-demo')
}

watch(
  () => props.lists,
  async () => {
    scale.value = 1
    await nextTick()
    setTimeout(() => {
      setCenter()
    }, 20)
  },
)

defineExpose({
  setCenter,
})
</script>

<template>
  <Transition name="fade">
    <div v-if="visible" ref="fullRef" class="full">
      <slot name="title">
        <ElPageHeader class="padding" title="返回" @back="clickBack">
          <template #content>
            <span>指标网络关系图</span>
          </template>
          <template #extra>
            <ElTooltip content="示例">
              <ElIcon size="21" style="margin-right: 10px" @click="clickDemo">
                <Help />
              </ElIcon>
            </ElTooltip>
            <ElTooltip content="全屏模式">
              <ElIcon size="20" @click="toggleMode">
                <FullScreen />
              </ElIcon>
            </ElTooltip>
          </template>
        </ElPageHeader>
      </slot>
      <div ref="boxRef" style="flex: 1; position: relative; overflow: hidden">
        <div
          ref="wrapRef"
          class="tree-wrap"
          :style="{
            width: `${wrapWidth}px`,
            transform:
              `translate(${left},${top}) scale(${scale})`,
          }"
          @mousewheel="onMousewheel"
        >
          <VueOkrTree
            v-for="(data, index) in lists"
            :key="index"
            :data="data"
            :render-content="treeNodeRender"
          />
        </div>
      </div>
    </div>
  </Transition>
</template>

<style scoped>
.full {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: var(--layout-container-bgc, #fff);
  z-index: 100;
  display: flex;
  flex-direction: column;
}
</style>
